<?php
namespace app\home\controller;
use cmf\controller\UserBaseController;
use think\Db;

class StreamController extends UserBaseController
{
    //查看流水应该是分权限的，暂时没有加
    function _initialize()
    {
        parent::_initialize();
    }
    public function index()
    {     
       $uinfo=cmf_get_current_user();
       $request = input('request.');
       /**搜索条件**/     
       $comeon = "1=1";
       if(!empty($uinfo['store_id'])){
           $comeon .=' and storeid ='.$uinfo['store_id'];
       }
       if(!empty($request['start_time'])){
           $comeon .= ' and DATE( FROM_UNIXTIME( ctime ) ) >= "'.$request['start_time'].'"';
       }else{
           $comeon .= ' and DATE( FROM_UNIXTIME( ctime ) ) >= "'.date('Y-m-d',time()).'"';
       }
       if(!empty($request['end_time'])){
           $comeon .= ' and DATE( FROM_UNIXTIME( ctime ) ) <= "'.$request['end_time'].'"';
       }
       //判断店长还是收银员
       $checkUser=get_dianzhang($uinfo['id'],$uinfo['store_id']);
       if(!$checkUser){
           $comeon .=' and operatorid ="'.$uinfo['id'].'"';
       }
       $comeon .=" and (payStatus =1 or payStatus =-3)";
       $list=Db::name('Order')->where($comeon)->order("id DESC")->paginate(8);
       $list->appends($request);
       
       
       $whereone='1=1';
       if(!empty($request['start_time'])){
           $whereone .= ' and DATE( FROM_UNIXTIME( ctime ) ) >= "'.$request['start_time'].'"';
       }else{
           $whereone .= ' and DATE( FROM_UNIXTIME( ctime ) ) >= "'.date('Y-m-d',time()).'"';
       }
       if(!empty($request['end_time'])){
           $whereone .= ' and DATE( FROM_UNIXTIME( ctime ) ) <= "'.$request['end_time'].'"';
       }
       $zonge = Db::name("Order")->where("payStatus=1")->where("storeid=".$uinfo['store_id'])->where($whereone)->field('sum(actualMoney) as sum')->find();  
      //echo Db::name("Order")->getlastsql();
       $totalMoney=Db::name("Order")->where("payStatus=1")->where("storeid=".$uinfo['store_id'])->where($whereone)->field('sum(totalMoney) as sum')->find();
       $zhekou=$totalMoney['sum']-$zonge['sum'];
       $num = Db::name("Order")->where("payStatus=1")->where("storeid=".$uinfo['store_id'])->where($whereone)->count();       

       $payType=array('1'=>'会员卡支付','2'=>'现金支付','3'=>'积分支付','4'=>'微信支付','5'=>'支付宝','6'=>'外卖支付');
       foreach($payType as $k=>$v){
           $total_money=Db::name('Order')->where('payType ='.$k)->where("payStatus=1")->where("storeid=".$uinfo['store_id'])->where($whereone)->sum('actualMoney');//该店铺该商品总营业额
           $type[$k]['total']=$total_money;
           $type[$k]['typename']=$v;
       }
       $this->assign("sum",$zonge);
       $this->assign("num",$num);
       $this->assign("uinfo",$uinfo);
       $this->assign("totalMoney",$totalMoney['sum']);
       $this->assign("zhekou",$zhekou);
       $this->assign("page", $list);
       $this->assign("list", $list);
       $this->assign("type", $type);
       return $this->fetch();
    }
    public function detail(){
        $param = $this->request->param();
        $id=$param['id'];
        $goodsname=isset($param['goodsname'])?$param['goodsname']:'';
        if ($goodsname){
            $where['g_goodsname']=['like',"%$goodsname%"];
            $g_list=Db::name('Goods')->where($where)->field('g_id')->select()->toarray();
            $g_id_arr=array();
            foreach ($g_list as $k=>$v){
                $g_id_arr[]=$v['g_id'];
            }
            $g_id_str=implode(',',$g_id_arr);
            $map['goodsid']=array('in',$g_id_str);
        }
        $orderNo=get_order_data($id,'orderNo');
        $map['orderid']=$orderNo;
        $detail_list=Db::name('OrderDetail')->where($map)->paginate(10);
        if($detail_list->toArray())
        {
            $detail_list->toArray();
            foreach($detail_list as $k=>$v){
                $data = array();
                $data = $v;
                $data['state_name'] = $this->getState($v['nature']);
                $detail_list->offsetSet($k,$data);
            }
        }                
        $page = $detail_list->render();
        $this->assign("detail_list", $detail_list);
        $this->assign("id", $id);
        $this->assign("page", $page);
        return $this->fetch();
    }
    function getState($id){
        if($id == 0){
            $name='无';
        }else{
            $name_str=DB::name('goods_state')->where(array('id'=>$id))->field('state_name')->find();
            $name=$name_str['state_name'];
        }
        return $name;
    }
    public function statis()
    {  
        $uinfo=cmf_get_current_user();
        $param = $this->request->param();
        $starttime=isset($param['start_time'])?$param['start_time']:'';
        $endtime=isset($param['end_time'])?$param['end_time']:'';
        $where=array();
        if(!empty($starttime)){
            $where['ctime'][]=array('egt',strtotime($starttime));
        }
        if(!empty($endtime)){
            $where['ctime'][]=array('lt',24*60*60+strtotime($endtime));
        }
        //判断店长还是收银员
        $checkUser=get_dianzhang($uinfo['id'],$uinfo['store_id']);
        if(!$checkUser){
            $where['operatorid']=$uinfo['id'];
        }
        $where['storeid']=$uinfo['store_id'];        
        $list=Db::name('OperatorStatis')->where($where)->order("id DESC,operatorid desc")->paginate(10); 
       // 获取分页显示
       $page = $list->render();
       $this->assign("uinfo", $uinfo);
       $this->assign("page", $page);
       $this->assign("list", $list);
       return $this->fetch();        
    }
    public function total(){
        $uinfo=cmf_get_current_user();
        $where=array();
        $param = $this->request->param();
        isset($param['start_time'])?$where['ctime'][]=array('egt',strtotime($param['start_time'])):'';
        isset($param['end_time'])?$where['ctime'][]=array('lt',24*60*60+strtotime($param['end_time'])):'';       
        $where['storeid'] = $uinfo['store_id'];
        $list=Db::name('TotalStatis')->where($where)->paginate(10); 
        $page = $list->render();
        $this->assign("uinfo", $uinfo);
        $this->assign("page", $page);
        $this->assign("list", $list);
        return $this->fetch();
    }
    /*
   *当天能退款
   * */
    public function refund(){
        $session=cmf_get_current_user();
        $ordeid=$this->request->param('id');
        $where['orderNo']=$ordeid;
        $old_order=DB::name('order')->where($where)->find();
        $data['payStatus']=-3;
        $today_time=strtotime('today');
        $night=$today_time+86400;
        if($old_order['ctime']>$today_time && $old_order['ctime']<$night)
        {
            //余额
            if($old_order['payType']==1)
            {
                $money=DB::name('finance_record')->where(['orderid'=>$ordeid])->field("sum(money) as money,userid,storeid")->select()->toArray();
                $cause['userid']=$money[0]['userid'];
                $cause['storeid']=$money[0]['storeid'];
                $old_finance=DB::name('finance')->where($cause)->field('money')->find();
                $new_money['money']=$old_finance['money']-$money[0]['money'];
                DB::name('finance')->where($cause)->update($new_money);
                //余额退款记录
                $finance_array['id'] =time().rand(1000,9999);
                $finance_array['userid']=$money[0]['userid'];
                $finance_array['orderid']=$ordeid;
                $finance_array['money']=-$money[0]['money'];
                $finance_array['storeid']=$money[0]['storeid'];
                $finance_array['remark']='退款';
                $finance_array['ctime']=time();
                $finance_array['operatorid']=$session['id'];
                DB::name('finance_record')->insert($finance_array);
            }
            //积分
            $integral=DB::name('integral_record')->where(['orderid'=>$ordeid])->field("SUM(num) as num,userid,storeid,cardid")->select()->toArray();
            if($integral[0]['userid'])
            {
                $cause['userid']=$integral[0]['userid'];
                $cause['storeid']=$integral[0]['storeid'];
                $old_integral=DB::name('integral')->where($cause)->field('num')->find();
                $new_integral['num']=$old_integral['num']-$integral[0]['num'];
                DB::name('integral')->where($cause)->update($new_integral);
                //积分退款记录
                $integral_array['id'] =time().rand(1000,9999);
                $integral_array['cardid'] =$integral[0]['cardid'];
                $integral_array['userid']=$integral[0]['userid'];
                $integral_array['orderid']=$ordeid;
                $integral_array['num']=-$integral[0]['num'];
                $integral_array['storeid']=$integral[0]['storeid'];
                $integral_array['remark']='退款';
                $integral_array['ctime']=time();
                $integral_array['operatorid']=$session['id'];
                DB::name('integral_record')->insert($integral_array);
            }
            DB::name('order_detail')->where(['orderid'=>$ordeid])->update(['paystatus'=>-3]);
            $state=DB::name('order')->where($where)->update($data);
            if($state)
            {
                $array='退款成功';
            }else{
                $array='退款成功';
            }
        }else{
            $array='超过退款时间';
        }
        $this->success($array);
    } 
    
}